What is @types/body-parser?
The @types/body-parser package contains TypeScript definitions for the body-parser package. Body-parser is a middleware used in Express applications to parse incoming request bodies before your handlers, available under the req.body property. It supports parsing of JSON, raw, text, and URL-encoded form bodies. The @types/body-parser package doesn't provide functionality by itself but offers type definitions to enable TypeScript developers to use body-parser in a type-safe manner.
What are @types/body-parser's main functionalities?
JSON Body Parsing
Parses incoming request bodies in a middleware before your handlers, available under the req.body property, assuming the Content-Type header of the request is application/json.
import * as bodyParser from 'body-parser';
import express from 'express';
const app = express();
app.use(bodyParser.json());
app.post('/json', (req, res) => {
res.send(req.body);
});
URL-Encoded Form Body Parsing
Parses incoming request bodies with URL-encoded data (like form submissions) before your handlers, making the form data available under the req.body property.
import * as bodyParser from 'body-parser';
import express from 'express';
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/form', (req, res) => {
res.send(req.body);
});
Other packages similar to @types/body-parser
express.json
Express 4.16.0 and higher ships with built-in middleware express.json() to parse JSON request bodies, similar to what body-parser's json() method does. It provides a native way within Express to accomplish what body-parser offers for JSON parsing without needing an external package.
express.urlencoded
Similar to express.json, express.urlencoded() is built into Express 4.16.0 and higher for parsing URL-encoded bodies. It serves as a native alternative to body-parser's urlencoded() method, allowing for parsing of URL-encoded form data directly within Express.